<?php

namespace common\observer;


use common\model\TaskModel;
use common\service\CommonService;
use support\SingletonTrait;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 分配工序任务计划完成时间被观察对象
 */
class TaskStepCategoryPlanEndTime implements SplObserver
{
    use SingletonTrait;

    /**
     * @inheritDoc
     */
    function update(SplSubject $subject): void
    {
        $updateTaskData = $subject->getSplUpdateData();
        if (empty($updateTaskData['plan_start_time']) || empty($updateTaskData['plan_end_time'])) {
            return;
        }
        $taskData = $subject->getSubjectData();
        // 查询环节最大计划结束时间
        $stepCategoryPlanTimeArr = model(TaskModel::class)->field('id,plan_start_time,plan_end_time')
            ->where(['entity_id' => $taskData['entity_id'], 'step_type' => 'step_category', 'step_category_id' => $taskData['step_category_id']])
            ->find();
        if (empty($stepCategoryPlanTimeArr)) {
            return;
        }
        if (!empty($taskData['plan_end_time']) && $taskData['plan_end_time'] == $stepCategoryPlanTimeArr['plan_end_time']) {
            return;
        }
        // 查询工序最后一道工序任务
        $stepMaxPlanTimeId = model(TaskModel::class)->field('max(id) as id')
            ->where(['entity_id' => $taskData['entity_id'], 'step_type' => 'step', 'step_category_id' => $taskData['step_category_id']])
            ->find();
        if (empty($stepMaxPlanTimeId)) {
            return;
        }
        // 最后一道工序的计划时间
        $stepPlanTimeArr = model(TaskModel::class)->field('id,plan_start_time,plan_end_time')
            ->where(['id' => $stepMaxPlanTimeId['id']])
            ->find();
        $stepCategoryPlanTimeArr['plan_start_time'] = date("Y-m-d H:i:s", $stepPlanTimeArr['plan_start_time']); // 工序任务最小计划开始时间
        $stepCategoryPlanTimeArr['plan_end_time'] = date("Y-m-d H:i:s", $stepPlanTimeArr['plan_end_time']); // 工序任务最大计划结束时间
        try {
            // 更新
            CommonService::instance('task')->update($stepCategoryPlanTimeArr, '', false);
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }

}
